package com.cxt.service.impl;

//import com.baomidou.entity.TripOrder;
//import com.baomidou.mapper.TripOrderMapper;TripOrderMapper
//import com.baomidou.service.ITripOrderService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cxt.Mapper.TripOrderMapper;
import com.cxt.context.BaseContext;
import com.cxt.dto.OrderDto;
import com.cxt.entity.*;
import com.cxt.service.*;
import com.cxt.vo.OrderInfoVo;
import com.cxt.vo.OrderListVo;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 行程订单表 服务实现类
 * </p>
 *
 * @author baomidou
 * @since 2025-02-27
 */
@Service
public class TripOrderServiceImpl extends ServiceImpl<TripOrderMapper, TripOrder> implements ITripOrderService {
    @Autowired
    private IAccountInfoService  accountInfoService;
    @Autowired
    private ICarpoolInfoService carpoolInfoService;
    @Autowired
    private IWaypointInfoService waypointInfoService;
    @Autowired
    private ITripInfoService tripInfoService;
    @Override
    @Transactional
    public void add(TripInfo one) {
        try {
            //获取司机的账户id
            LambdaQueryWrapper<AccountInfo> query = new LambdaQueryWrapper<>();
            query.eq(AccountInfo::getDriverId,one.getDriverId());
            AccountInfo accountInfo = accountInfoService.getOne(query);
            /**
             * 金额计算
             */
            //拼车信息
            LambdaQueryWrapper<CarpoolInfo> query1 = new LambdaQueryWrapper<>();
            query1.eq(CarpoolInfo::getId,one.getCarpoolInfoId());
            CarpoolInfo carpoolInfo = carpoolInfoService.getOne(query1);
            //行程信息
            BigDecimal totalPrice = new BigDecimal(0);
            if(carpoolInfo.getPricingMethod()==1){
                totalPrice = carpoolInfo.getFlatRate();
            }else if (carpoolInfo.getPricingMethod()==2){
                totalPrice =  carpoolInfo.getPricePerKm().multiply(one.getTraveledDistance())
                        .setScale(2, BigDecimal.ROUND_HALF_UP);
            }
            if(carpoolInfo.getIncludeTollFee()){
                totalPrice = totalPrice.add(carpoolInfo.getTollFee());
            }
            if(carpoolInfo.getPaymentCalculationMethod()==1){
                TripOrder build = TripOrder.builder()
                        .tripInfoId(one.getId())
                        .groupPurchaseId(one.getCarpoolInfoId())
                        .accountId(accountInfo.getId())
                        //团长
                        .userId(one.getGroupLeaderId())
                        .paymentAmount(totalPrice)
                        .paymentMethod(null)
                        .paymentStatus(0)
                        .orderGenerationTime(LocalDateTime.now())
                        .paymentTime(null)
                        .build();
                this.save(build);
            }else if(carpoolInfo.getPaymentCalculationMethod()==2){
                totalPrice = totalPrice.divide(BigDecimal.valueOf(carpoolInfo.getPassengerCount()),
                        2, BigDecimal.ROUND_HALF_UP);
                LambdaQueryWrapper<WaypointInfo> query2 = new LambdaQueryWrapper<>();
                query2.eq(WaypointInfo::getCarpoolInfoId,one.getCarpoolInfoId());
                List<WaypointInfo> list = waypointInfoService.list(query2);
                for (WaypointInfo waypointInfo : list) {
                    if(waypointInfo.getWaypointType()==3){
                        continue;
                    }
                    TripOrder build = TripOrder.builder()
                            .tripInfoId(one.getId())
                            .groupPurchaseId(one.getCarpoolInfoId())
                            .accountId(accountInfo.getId())
                            //拼车的用户
                            .userId(waypointInfo.getUserId())
                            .paymentAmount(totalPrice.multiply(BigDecimal.valueOf(waypointInfo.getPassengerCount()))
                                    .setScale(2, BigDecimal.ROUND_HALF_UP))
                            .paymentMethod(null)
                            .paymentStatus(0)
                            .orderGenerationTime(LocalDateTime.now())
                            .paymentTime(null)
                            .build();
                    this.save(build);
                }
            }
        }catch (BeansException e){
            throw new RuntimeException("订单生成失败，请联系客服");
        }
    }

    @Override
    public OrderListVo getOrderList() {
        OrderListVo orderListVo = new OrderListVo();
        //获取当前用户
        LambdaQueryWrapper<TripOrder> query = new LambdaQueryWrapper<>();
        query.eq(TripOrder::getUserId, BaseContext.getCurrentId());
        //未支付
        query.eq(TripOrder::getPaymentStatus,0);
        List<TripOrder> unpaidOrderList = this.list(query);
        orderListVo.setUnpaidOrderList(unpaidOrderList);
        query.clear();
        //以支付
        query.eq(TripOrder::getUserId, BaseContext.getCurrentId());
        query.eq(TripOrder::getPaymentStatus,1);
        List<TripOrder> paidOrderList = this.list(query);
        orderListVo.setPaidOrderList(paidOrderList);
        return orderListVo;
    }

    @Override
    public OrderInfoVo getOrderVo(Long id) {
        //查询订单信息
        TripOrder tripOrder = this.getById(id);
        //查询行程
        LambdaQueryWrapper<TripInfo> query = new LambdaQueryWrapper<>();
        query.eq(TripInfo::getId,tripOrder.getTripInfoId());
        TripInfo tripInfo = tripInfoService.getOne(query);
        //查询拼车
        LambdaQueryWrapper<CarpoolInfo> query1 = new LambdaQueryWrapper<>();
        query1.eq(CarpoolInfo::getId,tripInfo.getCarpoolInfoId());
        CarpoolInfo carpoolInfo = carpoolInfoService.getOne(query1);
        //查询拼车点
        LambdaQueryWrapper<WaypointInfo> query2 = new LambdaQueryWrapper<>();
        query2.eq(WaypointInfo::getCarpoolInfoId,tripInfo.getCarpoolInfoId());
        List<WaypointInfo> waypointInfoList = waypointInfoService.list(query2);
        return OrderInfoVo.builder()
                .tripInfo(tripInfo)
                .waypointInfoList(waypointInfoList)
                .tripOrder(tripOrder)
                .carpoolInfo(carpoolInfo)
                .isMine(tripOrder.getUserId().equals(BaseContext.getCurrentId()))
                .build();

    }

    @Override
    public OrderListVo getOrderListDriver() {
        //获取自己的账户
        Long currentId = BaseContext.getCurrentId();
        LambdaQueryWrapper<AccountInfo> query = new LambdaQueryWrapper<>();
        query.eq(AccountInfo::getDriverId,currentId);
        AccountInfo accountInfo = accountInfoService.getOne(query);
        if(accountInfo==null){
            throw new BeansException("账户不存在") {
            };
        }
        LambdaQueryWrapper<TripOrder> query1 = new LambdaQueryWrapper<>();
        query1.eq(TripOrder::getAccountId,accountInfo.getId());
        query1.eq(TripOrder::getPaymentStatus,0);
        List<TripOrder> tripOrderList = this.list(query1);
        LambdaQueryWrapper<TripOrder> query2 = new LambdaQueryWrapper<>();
        query2.eq(TripOrder::getAccountId,accountInfo.getId());
        query2.eq(TripOrder::getPaymentStatus,1);
        List<TripOrder> tripOrderList1 = this.list(query2);
        OrderListVo orderListVo = OrderListVo.builder()
                .unpaidOrderList(tripOrderList)
                .paidOrderList(tripOrderList1)
                .build();
        return orderListVo;
    }

    @Override
    @Transactional
    public boolean payTripOrder(OrderDto order) {
        //获取订单
        TripOrder tripOrder = this.getById(order.getId());
        if(tripOrder==null){
            return false;
        }
        //修改订单状态，调用账户收入方法
        tripOrder.setPaymentStatus(1);
        tripOrder.setPaymentMethod(order.getPaymentMethod());
        tripOrder.setPaymentTime(LocalDateTime.now());
        boolean b = this.updateById(tripOrder);
        Boolean b1 =accountInfoService.up(tripOrder.getAccountId(),tripOrder.getPaymentAmount(),1,"乘客支付订单");
        if(!b||!b1){
            throw new RuntimeException("支付失败");
        }
        return true;
    }
}
